package com.haiyou.common.valid.strategy;

import com.haiyou.common.exception.BusinessException;
import com.haiyou.common.valid.annotation.MultipartFileValid;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传参数验证策略
 **/
public class MultipartFileValidStrategy implements ValidStrategy {
    @Override
    public void doOperation(Object target, Object targetAnnotations) {
        MultipartFile arg = (MultipartFile) target;
        MultipartFileValid multipartFileValid = (MultipartFileValid) targetAnnotations;
        if (arg == null) {
            throw new BusinessException(multipartFileValid.message());
        }
        String suffix = FilenameUtils.getExtension(arg.getOriginalFilename());
        if (!multipartFileValid.type().contains(suffix.toLowerCase())) {
            throw new BusinessException("文件格式不对，只允许：" + multipartFileValid.type() + "格式");
        }
        if (multipartFileValid.size() == 0) {
            return;
        }
        if (multipartFileValid.size() < arg.getSize()) {
            throw new BusinessException("文件过大：" + multipartFileValid.size());
        }
    }
}